// pages/referee/referee.js
const request = require('../../utils/promise.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    username: '',  // 搜索框的昵称
    userArr: [
      // {id: 10001, username: '张三丰', checked: false},
      // {id: 10002, username: '李无敌', checked: false}
    ],
    userId: null,  // CheckBox 中选中的用户 id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 页面被用户分享时执行
   */
  onShareAppMessage() {
    return {
      title: '添加推荐人'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: '添加推荐人'
    }
  },

  /**
   * 根据昵称请求获取用户信息
   */
  reqSearchRefereUserData() {

    const param = {userId: wx.getStorageSync('userId'), username: this.data.username.trim()}
    request.GET('/user/query/users', param).then(res => {
      //console.log(res);
      if (res.data.resCode==200) {
        this.setData({
          userArr: res.data.userArrList
        })
      } else {
        wx.showToast({
          title: '搜索异常',
          icon: 'error',
          duration: 1500
        })
      }
    })
  },

  /**
   * 输入框值变化
   */
  bindSearchInput(e) {
    this.setData({
      username: e.detail.value
    })
    this.reqSearchRefereUserData();
  },

  /**
   * checkboxChange
   */
  checkboxChange(e) {

    const index = e.currentTarget.dataset.index;
    const refereeUserId = this.data.userArr[index].id;

    var arr = [];
    for (var i=0; i<this.data.userArr.length; i++) {
      var userItem = this.data.userArr[i];
      if (i==index) {
        userItem.checked = true;
      } else {
        userItem.checked = false;
      }
      arr.push(userItem);
    }

    this.setData({
      userId: refereeUserId,
      userArr: arr
    })
  },

  /**
   * 点击添加推荐人
   */
  clickAddReferee() {

    if (!this.data.userId) {
      wx.showToast({
        title: '请选择一个推荐人进行添加',
        icon: 'none'
      })
      return;
    }

    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 30000,
      mask: true
    })

    const param = {userId: wx.getStorageSync('userId'), refereeUserId: this.data.userId};
    request.GET('/user/referee/save', param).then(res => {
      //console.log(res)
      if (res.data.resCode==200) {
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 1000,
          mask: true
        })

        setTimeout(function(){
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      } else if (res.data.resCode==201) {
        wx.showToast({
          title: '推荐人注册时间不能小于您的注册时间',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      } else {
        wx.showToast({
          title: '保存异常错误',
          icon: 'error',
          mask: true
        })
      }
    })
  },
  
})